package edu.whu.demo.controller;
import java.io.FileOutputStream;
import java.io.IOException;

import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.whu.demo.domain.Activity;
import edu.whu.demo.domain.Message;
import edu.whu.demo.exception.ActivityAdminException;
import edu.whu.demo.exception.MessageException;
import edu.whu.demo.service.impl.ActivityServiceImpl;
import edu.whu.demo.service.impl.AuditService;
import edu.whu.demo.service.impl.MessageServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2022-11-24
 */
@RestController
@RequestMapping("/activity")
@CrossOrigin
public class ActivityController {
    //!!!需要异常处理，否则要返回ResponseEntity

    @Autowired
    AuditService auditService;

    @Autowired
    MessageServiceImpl messageService;

    @Autowired
    ActivityServiceImpl activityService;
    @Value("${PicPath.local}")
    String localPath;
    @Value("${PicPath.remote}")
    String remotePath;
    @Value("${server.port}")
    String port;
    @Value("${MyDomain}")
    String domain;


    @ApiOperation("设置图片")
    @PostMapping("/setpic")
//    @PreAuthorize("hasRole('normal')")
    public boolean addActivity(@RequestParam("id") Long id,@RequestParam("count")Integer count, @RequestPart("pic") MultipartFile pic) throws IOException, MessageException {
        Activity activity = activityService.getById(id);
        String fileName =  UUID.randomUUID()+".png";
        FileOutputStream fileOutputStream = new FileOutputStream(localPath+fileName);
        fileOutputStream.write(pic.getBytes());


        try{
        switch (count){
            case 1:{
                if(auditService.pictureAudit(localPath+fileName)){
                   activity.setState("released");
                    System.out.println("图片1审核通过");
                }
                else{
                    activity.setState("checking");
                    System.out.println("图片1审核未通过");
                }
                activity.setPic1("http://"+domain+":"+port+"/"+remotePath+fileName);
                activityService.updateActivity(id,activity);
                return true;
            }
            case 2:{
                if(!Objects.equals(activity.getState(), "released") ||!auditService.pictureAudit(localPath+fileName)){
                    activity.setState("checking");
                    System.out.println("图片2审核不通过");
                }
                activity.setPic2("http://"+domain+":"+port+"/"+remotePath+fileName);
                activityService.updateActivity(id,activity);
                return true;

            }
            case 3:{
                if(!Objects.equals(activity.getState(), "released") ||!auditService.pictureAudit(localPath+fileName)){
                    activity.setState("checking");
                    System.out.println("图片3审核不通过");
                }
                activity.setPic3("http://"+domain+":"+port+"/"+remotePath+fileName);
                activityService.updateActivity(id,activity);
                return true;
            }
            default:break;
        }
        }
        catch (ActivityAdminException e){
            throw new RemoteException(e.getMessage());
        }
        if(activity.getState().equals("released")) {
            Message message = new Message();
            message.setType("check");
            message.setToUid(activity.getHostUid());
            message.setFromUid((long) -1);
            message.setActivityId(activity.getId());
            message.setTime(LocalDateTime.now());
            message.setIsRead(0);
            message.setContent("活动审核通过!");
            messageService.addMessage(message);
        }
        return false;
    }


    @ApiOperation("添加活动主体")
    @PostMapping("")
//    @PreAuthorize("hasRole('normal')")

    public Activity addActivity(@RequestBody Activity activity) throws MessageException {
        boolean verify = true;


        if(!auditService.textAudit(activity.getInfo())){
            System.out.println("简介审核不通过");
            verify = false;
        };
        if(verify&&!auditService.textAudit(activity.getContent())){
            System.out.println("内容审核不通过");
            verify = false;
        }
        if(verify&&!auditService.textAudit(activity.getName())){
            System.out.println("名字审核不通过");
            verify = false;
        }
        if(verify){
            activity.setState("released");
            System.out.println("文本审核通过");
        }

        Activity activity1 = activityService.addActivity(activity);



        return activity1;
    }


    @GetMapping("")
    public IPage<Activity> serachActivity(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required=false) String keyword,
            @RequestParam(required=false) String type,
            @RequestParam(required=false) String orderBy,
            @RequestParam(required=false) Boolean sequence,
            @RequestParam(required = false) Integer state,
            @RequestParam(required=false) Boolean byUsername,
            @RequestParam(required=false) Long hostUid
    ){
        Map<String,Object> condition = new HashMap<>();
        if(!"".equals(keyword)){
            condition.put("keyword",keyword);
        }
        if(!"".equals(type)){
            condition.put("type",type);
        }
        if(!"".equals(orderBy)){
            condition.put("orderBy",orderBy);
            condition.put(orderBy,sequence);
        }
        if(byUsername){
            condition.put("byUsername",byUsername);
        }
        if(state!=null){
            condition.put("state", state);
        }
        if(hostUid!=null){
            condition.put("hostUid", hostUid);
        }
        return activityService.findActivity(condition,pageNum,pageSize);
    }

    @ApiOperation("修改活动")
    @PostMapping("/{id}")
    public void updateActivity(@PathVariable Long id, @RequestBody Activity activity) throws ActivityAdminException, MessageException {
        Activity temp = activityService.getById(id);
        boolean verify = true;
        if(!auditService.textAudit(activity.getInfo())){
            System.out.println("简介审核不通过");
            verify = false;
        };
        if(verify&&!auditService.textAudit(activity.getContent())){
            System.out.println("内容审核不通过");
            verify = false;
        }
        if(verify&&!auditService.textAudit(activity.getName())){
            System.out.println("名字审核不通过");
            verify = false;
        }
        if(verify){
            activity.setState("released");
            System.out.println("文本审核通过");
        }
        if(verify){
        activityService.updateActivity(id,activity);
        Message message = new Message();
        message.setActivityId(id);
        message.setTime(LocalDateTime.now());
        message.setFromUid(activity.getHostUid());
        message.setContent(activityService.getChangeContent(temp,activity));
        message.setIsRead(0);
        message.setType("change");
        messageService.addMessage(message);
        }
    }

    @ApiOperation("删除活动")
    @DeleteMapping("/{id}")
    public void deleteActivity(@PathVariable long id) throws ActivityAdminException {
        activityService.deleteActivity(id);
    }

    @ApiOperation("获得单个活动")
    @GetMapping("/{id}")
    public Activity getActivityById(@PathVariable long id){
        return activityService.getById(id);
    }


    @ApiOperation("审核活动")
    @PutMapping("/verify/{id}")
    @PreAuthorize("hasRole('admin')")
    public void verifyActivity(@PathVariable Long id, @RequestParam Boolean verify) throws ActivityAdminException, MessageException {

        activityService.verifyActivity(id,verify);
    }
}

